package com.community.comsys.controller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.community.common.annotation.Log;
import com.community.common.core.controller.BaseController;
import com.community.common.core.domain.AjaxResult;
import com.community.common.enums.BusinessType;
import com.community.comsys.domain.House;
import com.community.comsys.service.IHouseService;
import com.community.common.utils.poi.ExcelUtil;
import com.community.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.community.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 房屋管理Controller
 * 
 * @author 潇东
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/comsys/house")
public class HouseController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(HouseController.class);
    
    @Autowired
    private IHouseService houseService;
    
    @Autowired
    private RedisCache redisCache;
    
    // 缓存键前缀
    private static final String CACHE_KEY_PREFIX = "comsys:house:";
    // 缓存过期时间（分钟）
    private static final int CACHE_TIMEOUT = 30;

    /**
     * 房屋状态统计
     */
    @GetMapping("/groupByStatus")
    public AjaxResult groupByStatus(){
        String cacheKey = CACHE_KEY_PREFIX + "groupByStatus";
        
        // 尝试从缓存获取
        Object cachedResult = redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            log.info("✅ 从Redis缓存获取房屋状态统计数据");
            return success(cachedResult);
        }
        
        // 缓存未命中，从数据库查询
        Object result = houseService.groupByStatus();
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("房屋状态统计数据已缓存到Redis");
        
        return success(result);
    }

    /**
     * 根据社区分类查询房屋数量
     */
    @GetMapping("/groupByCommunity")
    public AjaxResult groupByCommunity(){
        String cacheKey = CACHE_KEY_PREFIX + "groupByCommunity";
        
        // 尝试从缓存获取
        Object cachedResult = redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            log.info("✅ 从Redis缓存获取社区房屋数量统计数据");
            return success(cachedResult);
        }
        
        // 缓存未命中，从数据库查询
        Object result = houseService.groupByCommunity();
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("社区房屋数量统计数据已缓存到Redis");
        
        return success(result);
    }

    /**
     * 统计房屋数量
     */
    @GetMapping("/count")
    public AjaxResult count(){
        String cacheKey = CACHE_KEY_PREFIX + "count";
        
        // 尝试从缓存获取
        Integer cachedCount = redisCache.getCacheObject(cacheKey);
        if (cachedCount != null) {
            log.info("✅ 从Redis缓存获取房屋数量统计");
            return success(cachedCount);
        }
        
        // 缓存未命中，从数据库查询
        Long count = houseService.count();
        Integer result = count.intValue();
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("房屋数量统计已缓存到Redis");
        
        return success(result);
    }
    
    /**
     * 生成缓存键
     */
    private String generateCacheKey(String operation, Object param) {
        StringBuilder key = new StringBuilder(CACHE_KEY_PREFIX);
        key.append(operation);
        
        if (param != null) {
            // 简单的缓存键生成策略，可以根据实际需求调整
            key.append(":").append(param.toString().hashCode());
        }
        
        return key.toString();
    }
    
    /**
     * 清除所有房屋相关缓存
     */
    private void clearHouseCache() {
        log.info("清除房屋相关所有缓存");
        // 获取所有房屋相关的缓存键并删除
        redisCache.deleteObject(redisCache.keys(CACHE_KEY_PREFIX + "*"));
    }


    /**
     * 查询房屋管理列表
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:list')")
    @GetMapping("/list")
    public TableDataInfo list(House house)
    {
        // 生成缓存键，包含查询参数的标识
        String cacheKey = generateCacheKey("list", house);
        log.info("生成的缓存key: {}", cacheKey);
        
        // 尝试从缓存获取
        TableDataInfo cachedResult = redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            log.info("✅ 从Redis缓存获取房屋列表数据");
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        startPage();
        List<House> list = houseService.selectHouseList(house);
        TableDataInfo result = getDataTable(list);
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("房屋列表数据已缓存到Redis");
        
        return result;
    }

    /**
     * 导出房屋管理列表
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:export')")
    @Log(title = "房屋管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, House house)
    {
        List<House> list = houseService.selectHouseList(house);
        ExcelUtil<House> util = new ExcelUtil<House>(House.class);
        util.exportExcel(response, list, "房屋管理数据");
    }


    /**
     * 导入楼宇列表
     * @param file
     * @return
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:import')")
    @Log(title = "房屋管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile file){
        try {
            ExcelUtil<House> util = new ExcelUtil<>(House.class);
            // 通过ExcelUtil工具类解析上传的Excel文件，将文件内容转换为Community对象列表
            List<House> HouseList = util.importExcel(file.getInputStream());
            // 处理导入的数据
            int result = houseService.importHouseList(HouseList);
            
            if (result > 0) {
                // 导入成功，清除所有缓存
                clearHouseCache();
            }
            
            return success(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取房屋管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:query')")
    @GetMapping(value = "/{houseId}")
    public AjaxResult getInfo(@PathVariable("houseId") Long houseId)
    {
        String cacheKey = CACHE_KEY_PREFIX + "info:" + houseId;
        
        // 尝试从缓存获取
        House cachedHouse = redisCache.getCacheObject(cacheKey);
        if (cachedHouse != null) {
            log.info("✅ 从Redis缓存获取房屋详情数据，ID: {}", houseId);
            return success(cachedHouse);
        }
        
        // 缓存未命中，从数据库查询
        House house = houseService.selectHouseByHouseId(houseId);
        
        // 缓存查询结果
        if (house != null) {
            redisCache.setCacheObject(cacheKey, house, CACHE_TIMEOUT, TimeUnit.MINUTES);
            log.info("房屋详情数据已缓存到Redis，ID: {}", houseId);
        }
        
        return success(house);
    }

    /**
     * 新增房屋管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:add')")
    @Log(title = "房屋管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody House house)
    {
        int result = houseService.insertHouse(house);
        if (result > 0) {
            // 新增成功，清除所有缓存
            clearHouseCache();
        }
        return toAjax(result);
    }

    /**
     * 修改房屋管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:edit')")
    @Log(title = "房屋管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody House house)
    {
        int result = houseService.updateHouse(house);
        if (result > 0) {
            // 修改成功，清除所有缓存
            clearHouseCache();
            
            // 也可以只清除特定房屋的缓存
            if (house.getHouseId() != null) {
                String specificCacheKey = CACHE_KEY_PREFIX + "info:" + house.getHouseId();
                redisCache.deleteObject(specificCacheKey);
                log.info("已清除特定房屋缓存，ID: {}", house.getHouseId());
            }
        }
        return toAjax(result);
    }

    /**
     * 删除房屋管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:house:remove')")
    @Log(title = "房屋管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{houseIds}")
    public AjaxResult remove(@PathVariable Long[] houseIds)
    {
        int result = houseService.deleteHouseByHouseIds(houseIds);
        if (result > 0) {
            // 删除成功，清除所有缓存
            clearHouseCache();
            
            // 也可以清除特定房屋的缓存
            for (Long houseId : houseIds) {
                String specificCacheKey = CACHE_KEY_PREFIX + "info:" + houseId;
                redisCache.deleteObject(specificCacheKey);
                log.info("已清除特定房屋缓存，ID: {}", houseId);
            }
        }
        return toAjax(result);
    }
}
